﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace N2.Workflow
{
	using Items;

	partial class WorkflowProvider : IWorkflowProvider
	{
		IItemState IWorkflowProvider.GetCurrentState(ContentItem item)
		{
			return this.GetCurrentState(item) as IItemState;
		}

		StateType IWorkflowProvider.GetLatestState<StateType>(ContentItem item)
		{
			return
				this.GetHistory(item)
					.OfType<StateType>()
					.OrderBy(_state => _state.Created)
					.LastOrDefault();
		}

		IItemState IWorkflowProvider.GetLatestState(ContentItem item, Type stateType)
		{
			return
				Find.Items
					.Where
					.Parent.Eq(item)
					.And
					.Type.Eq(stateType)
					.Select<ItemState>()
					.OrderBy(_state => _state.Created)
					.LastOrDefault() as IItemState;
		}
		
		IEnumerable<IItemState> IWorkflowProvider.GetHistory(ContentItem item)
		{
			return this.GetHistory(item).Cast<IItemState>();
		}
		
		IItemState IWorkflowProvider.PerformAction(
			ContentItem item, string actionName, object values)
		{
			return this.PerformActionInternal(item, ActionArguments.ByName(actionName, values));
		}

		IItemState IWorkflowProvider.PerformAction(
			ContentItem item, IItemState newState)
		{
			return this.PerformActionInternal(item, ActionArguments.ByState(newState));
		}

		IWorkflowDefinition IWorkflowProvider.GetDefinition(ContentItem item)
		{
			return this.GetDefinition(item) as IWorkflowDefinition;
		}
		
		IActionDefinition IWorkflowProvider.ResolveActionForItem(ContentItem item, string actionName)
		{
			return this.ResolveActionForItem(item, actionName) as IActionDefinition;
		}
	}
}
